package com.pig4cloud.pig.module.controller.estate;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.estate.Worker;
import com.pig4cloud.pig.module.api.entity.wx.UserMp;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.estate.IWorkerService;
import com.pig4cloud.pig.module.service.wx.IUserMpService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.RequiredArgsConstructor;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 小区工作人员表Controller
 *
 * @author ruoyi
 * @date 2021-09-03
 */
@Validated
@Api(value = "小区工作人员表控制器", tags = {"小区工作人员表管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/worker")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class WorkerController {

    private final IWorkerService workerService;
//	private final ISysDictDataService sysDictDataService;
	private final IEstateService estateService;
	private final IWxUserService wxUserService;
	private final IUserMpService userMpService;

    /**
     * 查询小区工作人员表列表
     */
    @ApiOperation("查询小区工作人员表列表")
    @PreAuthorize("@pms.hasPermission('module:worker:list')")
    @GetMapping("/list")
    public TableDataInfo<Worker> list(@Validated Worker worker) {
		PigUser sysUser = SecurityUtils.getUser();
        QueryWrapper<Worker> qw = new QueryWrapper<>();
        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        } else if(sysUser.getUserType() == 4){//商家
            qw.eq("mer_id",sysUser.getMerId());
        }else{
        	if(worker.getEstateId()!=null){
				qw.eq("estate_id", worker.getEstateId());
			}
		}

		if(worker.getUserType() != null){
			qw.eq("user_type",worker.getUserType());
		}
		if(StrUtil.isNotEmpty(worker.getWorkerType())){
			qw.eq("worker_type",worker.getWorkerType());
		}
		if(StrUtil.isNotEmpty(worker.getWorkerName())){
			qw.and(wrapper->{
				qw.like("worker_name",worker.getWorkerName()).or().like("worker_phone",worker.getWorkerName());
			});
		}
		TableDataInfo<Worker> td = PageUtils.buildDataInfo(workerService.page(PageUtils.buildPage(),qw));
		List<Worker> list= td.getData();
		list.forEach(worker1 -> {
			Estate estate = estateService.findById(worker1.getEstateId());
			if(estate!=null){
				worker1.setEstateName(estate.getEstateName());
			}

			if(StrUtil.isNotEmpty(worker1.getNickName())){
				worker1.setNickName(EmojiParser.parseToUnicode(worker1.getNickName()));
			}
			if(StrUtil.isNotEmpty(worker1.getWorkerType())){
//				worker1.setWorkerTypeName(sysDictDataService.selectDictLabel("worker_type",worker1.getWorkerType()));
			}

			worker1.setIsFocus(0);
			QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
			qwMp.eq("open_id",worker1.getMpOpenId());
			qwMp.last("limit 1");
			UserMp userMp = userMpService.getOne(qwMp);
			if(userMp!=null){
				worker1.setIsFocus(1);
			}

		});
        return td;
    }

	/**
	 * 查询小区工作人员表列表
	 */
	@ApiOperation("查询小区工作人员表列表")
	@PreAuthorize("@pms.hasPermission('module:worker:list')")
	@GetMapping("/listByEstate")
	public R listByEstate(@Validated Worker worker) {
		QueryWrapper<Worker> qw = new QueryWrapper<>();
		if(worker.getEstateId() != null){
			qw.eq("estate_id",worker.getEstateId());
		}
		List<Worker > list = workerService.list(qw);
		return R.ok(list);
	}

    /**
     * 获取小区工作人员表详细信息
     */
    @ApiOperation("获取小区工作人员表详细信息")
    @PreAuthorize("@pms.hasPermission('module:worker:query')")
    @GetMapping("/{id}")
    public R<Worker> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Worker worker = workerService.getById(id);
        return R.ok(worker);
    }

    /**
     * 新增小区工作人员表
     */
    @ApiOperation("新增小区工作人员表")
    @PreAuthorize("@pms.hasPermission('module:worker:add')")
    @SysLog("小区工作人员表")
    @PostMapping()
    public R<Void> add(@Valid @RequestBody Worker worker) {
		WxUser wxUser = wxUserService.findById(worker.getWxUserId());
		if(wxUser!=null){
			if(StrUtil.isNotEmpty(wxUser.getNickName())){
				worker.setNickName(EmojiParser.parseToAliases(wxUser.getNickName()));
			}
			QueryWrapper<UserMp> qw = new QueryWrapper<>();
			qw.eq("union_id",wxUser.getUnionId());
			qw.last("limit 1");
			UserMp userMp = userMpService.getOne(qw);
			if(userMp!=null){
				worker.setMpOpenId(userMp.getOpenId());
			}
		}
        return R.okByRow(workerService.save(worker) ? 1 : 0);
    }

    /**
     * 修改小区工作人员表
     */
    @ApiOperation("修改小区工作人员表")
    @PreAuthorize("@pms.hasPermission('module:worker:edit')")
    @SysLog("小区工作人员表")
    @PutMapping()
    public R<Void> edit(@Valid @RequestBody Worker worker) {
		WxUser wxUser = wxUserService.findById(worker.getWxUserId());
		if(wxUser!=null){
			if(StrUtil.isNotEmpty(wxUser.getNickName())){
				worker.setNickName(EmojiParser.parseToAliases(wxUser.getNickName()));
			}
			QueryWrapper<UserMp> qw = new QueryWrapper<>();
			qw.eq("union_id",wxUser.getUnionId());
			qw.last("limit 1");
			UserMp userMp = userMpService.getOne(qw);
			if(userMp!=null){
				worker.setMpOpenId(userMp.getOpenId());
			}
		}
        return R.okByRow(workerService.updateById(worker) ? 1 : 0);
    }

    /**
     * 删除小区工作人员表
     */
    @ApiOperation("删除小区工作人员表")
    @PreAuthorize("@pms.hasPermission('module:worker:remove')")
    @SysLog("小区工作人员表")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(workerService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
